package org.zjt.mock.demo.mock.config;

import com.alibaba.fastjson.JSON;
import io.reactivex.Maybe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.zjt.mock.demo.mock.exception.MockAppException;
import org.zjt.mock.demo.mock.vo.ResultMsg;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.PrintWriter;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-06-21 下午2:19
 * @see
 */
@Slf4j
public class ExceptionHandleStrategies {


    public Maybe<String> handle(Throwable throwable){
        if (throwable instanceof ConstraintViolationException){
            ConstraintViolationException constraintViolationException = ConstraintViolationException.class.cast(throwable);
            Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
            if (!CollectionUtils.isEmpty(constraintViolations)){
                String errorMsg = String.join(",", constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()));
                log.error("validate error msg :{}",errorMsg);
                return StringUtils.isEmpty(errorMsg) ? Maybe.empty() : Maybe.just(errorMsg);
            }else{
                log.error("validate exception,but  constraintViolations is empty :{}",constraintViolations);
                return Maybe.empty();
            }
        }else if (throwable instanceof MockAppException){
            MockAppException mockAppException = MockAppException.class.cast(throwable);
            log.error("系统内部异常",mockAppException);
            String message = mockAppException.getMessage();
            return StringUtils.isEmpty(message) ? Maybe.empty() : Maybe.just(message);
        }else{
            log.error("undefined teach exception",throwable);
            log.error("undefined teach exception:{}",throwable.getClass().getName());
            return Maybe.empty();
        }
    }


    /**
     * 产生一个异常处理器
     * @param errorMsgSupplier
     * @return
     */
    public Consumer<HttpServletResponse> generateHandler(Supplier<Maybe<String>> errorMsgSupplier){
        return httpServletResponse -> errorMsgSupplier.get().subscribe(errorMsg ->{
            errorMsg = StringUtils.isEmpty(errorMsg) ? "操作异常，请稍后再试" : errorMsg ;
            errorMsg = JSON.toJSONString(ResultMsg.error(errorMsg));
            httpServletResponse.setCharacterEncoding("utf-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(errorMsg);
        });
    }


}
